package com.appium.manager.element.config;

import com.appium.manager.element.ElementHelper;
import com.appium.manager.element.config.ymlHandler.ElementBinderConfig;
import com.appium.manager.element.config.ymlHandler.ElementMappingHandler;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.WebElement;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *     YML中配置每个测试中需要用到的元素的定位方式和定位用的key
 *
 * </p>
 * @author 大忽悠
 * @create 2022/7/8 8:59
 */
public class YmlElementBinder extends ElementHelper {

    private ElementMappingHandler mappingHandler=new ElementMappingHandler();

    private ElementBinderConfig binderConfig;

    private Map<String,WebElement> cache=new HashMap<>();

    private static final String BINDER_SEPARATOR="=";

    private String curTestClassName;

    public YmlElementBinder(AndroidDriver<WebElement> androidDriver) {
        super(androidDriver);
        binderConfig=new ElementBinderConfig();
    }

    public YmlElementBinder(AndroidDriver<WebElement> androidDriver, String testDataFilePath,String dataBinderYmlFilePath) {
        super(androidDriver, testDataFilePath);
        binderConfig=new ElementBinderConfig(dataBinderYmlFilePath);
    }

    public void setCurTestClassName(String curTestClassName) {
        this.curTestClassName = curTestClassName.replace(".","-");
    }

    /**
     * 通过元素绑定的配置文件来根据指定key获取指定元素
     */
    public WebElement getElement(String key) throws InvocationTargetException, IllegalAccessException, InterruptedException {
        key=curTestClassName+"."+key;
        WebElement webElement=null;
        if(cache.containsKey(key)){
            return cache.get(key);
        }else {
            webElement = doGetElement(key);
            cache.put(key,webElement);
        }
        return webElement;
    }

    private WebElement doGetElement(String key) throws IllegalAccessException, InvocationTargetException {
        String locateWay = binderConfig.getElementLocateWay(key);
        String[] split = locateWay.split(BINDER_SEPARATOR);
        if(split.length!=2){
            throw new RuntimeException("元素查找绑定配置文件中,对应格式为: 查找方式=具体定位用到的字符串,例如: id=button5");
        }
        Method locateMethod = mappingHandler.getLocateMethod(split[0]);
        WebElement webElement = (WebElement) locateMethod.invoke(this, split[1]);
        return webElement;
    }
}
